package com.semidata.rtd.core.http.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.timeout.ReadTimeoutHandler;

import java.util.concurrent.TimeUnit;

public class HttpClientInitializer extends ChannelInitializer<SocketChannel> {

    private HttpResponseHandler handler;
    private long timeout;

    public HttpClientInitializer(HttpResponseHandler handler) {
        this(handler, 0);
    }

    public HttpClientInitializer(HttpResponseHandler handler, long timeout) {
        this.handler = handler;
        this.timeout = timeout;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();

        p.addLast("codec", new HttpClientCodec());

        // Remove the following line if you don't want automatic content
        // decompression.
        // p.addLast("inflater", new HttpContentDecompressor());

        if (timeout > 0)
            p.addLast("timeout", new ReadTimeoutHandler(timeout, TimeUnit.MILLISECONDS));

        p.addLast("handler", new HttpClientHandler(handler));

    }

}
